<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/html">
<head>
    <title>人脸检测</title>
    <#import "common/common.macro.ftl" as netCommon>
    <@netCommon.commonStyle />
</head>

</head>
<body class="hold-transition sidebar-mini layout-fixed">
<div class="wrapper">
    <!-- Main Sidebar Container -->
    <@netCommon.commonSidebar "人脸识别" />
    <div class="content-wrapper">
        <h4 align="center" style="margin-top: 30px">
            人脸识别示例
        </h4>

        <div class="imageDiv">
            <div id="baseImg" class="base-img"></div>
            <img id="img" class="target-img"/>
        </div>


        <div>

            <span class="selectDiv" style="margin-left: 200px">选择图片：</span>

            <div class="selectDiv" style="margin-left: 20px">
                <input class="fileInput" type="file" accept="image/png, image/jpeg" value="" onchange="fileInput()">
            </div>


        </div>

    </div>

</div>

<@netCommon.commonScript />

<script>


    let img = document.getElementById('img');

    let firstImg = new Image();
    firstImg.src = 'images/zhaoyang.jpg'

    firstImg.onload = function () {
        faceRecognition(this)
    }

    function faceRecognition(image) {
        let canvas = document.createElement('canvas');
        canvas.width = image.width;
        canvas.height = image.height;
        let ctx = canvas.getContext("2d");
        ctx.drawImage(image, 0, 0, image.width, image.height)

        $.post("/faceRecognition", {image: canvas.toDataURL("image/png")}, function (result) {
            console.info(result)
            $('#baseImg').empty()
            if (result.code === 0 && result.data.length > 0) {
                result.data.forEach(r => {
                    let rect = r.rect;
                    let x = rect.left;
                    let y = rect.top;
                    let w = rect.right - rect.left;
                    let h = rect.bottom - rect.top;
                    ctx.strokeStyle = "#FF0000";
                    ctx.lineWidth = 2;
                    let fontSize = 20
                    if (w >= 300) {
                        fontSize = w / 6;
                    }
                    ctx.strokeRect(x, y, w, h);
                    ctx.fillStyle = "#00FF00";
                    ctx.font = fontSize + "px Georgia";
                    let gender = '未知'
                    if (r.gender === 0) {
                        gender = '男'
                    } else if (r.gender === 1) {
                        gender = '女'
                    }
                    let liveness = '未知'
                    if (r.liveness === 0) {
                        liveness = '非活体'
                    } else if (r.liveness === 1) {
                        liveness = '活体'
                    } else if (r.liveness === -2) {
                        liveness = '超出人脸'
                    }

                    let txt = (r.name === undefined ? '未知' : r.name) + ',' + gender + ',' + r.age + ',' + liveness;
                    console.log("姓名:" + r.name)
                    ctx.fillText(txt, x, y - 10);
                    //显示匹配的底库
                    let baseImgPath = r.baseImgPath;
                    if (typeof baseImgPath !== "undefined" && baseImgPath !== null && baseImgPath !== "") {
                        var imgText = "<img id='" + r.faceId + "' class='base-img-detail'/>";
                        $('#baseImg').append(imgText);
                        $('#' + r.faceId).attr("src", "../" + baseImgPath);
                        $('#baseImg').show();
                    }

                });
            }
            img.src = canvas.toDataURL("image/png");

        });
    }

    function fileInput() {
        let file = $(".fileInput")[0].files[0];
        let that = this;
        compressFile(file, function (obj) {
            console.log(obj)
            file = obj
            let reader = new FileReader();
            reader.readAsDataURL(file);
            reader.onload = function () {
                let image = new Image();
                image.src = reader.result;
                image.onload = function () {
                    faceRecognition(image);
                }
            }
            that.value = '' // 加不加都行，解决无法上传重复图片的问题。
        })
    }

    /**
     * 压缩图片
     * @param file input获取到的文件
     * @param callback 回调函数，压缩完要做的事，例如ajax请求等。
     */
    function compressFile(file, callback) {
        let fileObj = file;
        let reader = new FileReader()
        reader.readAsDataURL(fileObj) //转base64
        reader.onload = function (e) {
            let image = new Image() //新建一个img标签（还没嵌入DOM节点)
            image.src = e.target.result
            image.onload = function () {
                let width = image.width;
                let height = image.height;
                console.log("image.width:" + image.width);
                console.log("image.height:" + image.height)
                //大于指定尺寸才压缩
                if (width >= 1500) {
                    width = width / 6
                    height = height / 6
                }
                // 新建canvas
                let canvas = document.createElement('canvas'),
                    context = canvas.getContext('2d'),
                    imageWidth = width,
                    imageHeight = height,
                    data = ''
                canvas.width = imageWidth
                canvas.height = imageHeight
                context.drawImage(image, 0, 0, imageWidth, imageHeight)
                data = canvas.toDataURL('image/jpeg') // 输出压缩后的base64
                let arr = data.split(','), mime = arr[0].match(/:(.*?);/)[1], // 转成blob
                    bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
                while (n--) {
                    u8arr[n] = bstr.charCodeAt(n);
                }
                let files = new window.File([new Blob([u8arr], {type: mime})], 'test.jpeg', {type: 'image/jpeg'}) // 转成file
                callback(files) // 回调
            }
        }
    }

</script>

<style>

    .content-wrapper {
        width: 800px;
        background-color: #ffffff;
    }

    .selectDiv {
        display: inline;
    }

    .imageDiv {
        width: 1200px;
        height: 440px;
        margin-left: 20px;
        margin-top: 20px;
        margin-bottom: 20px;
        /*background-color: #1aa67d;*/
        display: flex;
        align-items: center;
        justify-content: center;
        /*为了效果明显，可以将如下边框打开，看一下效果*/
        border: 1px solid black;
    }

    .base-img {
        display: flex;
        flex-flow: row;
        align-items: center;
        justify-content: center;
        margin-right: 10px;
        width: 600px;
        height: 440px;
    }
    .base-img-detail {
        width: 128px;
        height: 128px;
    }

    .target-img {
        width: auto;
        height: 440px;
    }

</style>

</body>
</html>
